package com.java.controller; /**
 * @author 周明
 * @create 2022-10-2022-10-2915:10
 */

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methodName;
        //接收web请求地址
        String uri = request.getRequestURI();
        int i = uri.lastIndexOf(".");
        if(i==-1){//刚启动或者调用servlet中的crud,其它的css,js,图片等不用管了……
            if(uri.equals("/mysc/")){//判断当前项目启动地址是否为：/mysc/
                methodName="query";//指定启动要调用的方法为findGoods
            }else {//否则用户调用哪个方法，就把哪个方法名截取出来调用
                methodName = uri.substring(uri.lastIndexOf("/") + 1);//得到请求名字add,update,delete,query
            }
            try {
                //反射方法调用
                Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
                method.invoke(this,request,response);//调用方法,相当于实例化对象名.方法名()
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
    //@Override
    //protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //    doGet(request,response);
    //}
}
